<?php
class Page_Model_Page extends Zend_Db_Table_Abstract
{
	protected $_name = 'page';

	public function insert(array $data)
	{
		//TODO : code to clean data before insert here

		$data['date_created'] = date('Y-m-d H:i:s');
		$data['site_id'] = App_Functions::getSiteId();
		parent::insert($data);
	}

	public function update(array $data, $where = null)
	{
		//TODO : code to clean data before update here

		$data['date_updated'] = date('Y-m-d H:i:s');
		parent::update($data, $where);
	}

	public function fetchById($id)
	{
		$row = $this->find((int)$id)->current()->toArray();
		return $row;
	}

	public function deleteById($id)
	{
		$data['date_deleted'] = date('Y-m-d H:i:s');
		$data['isvisible'] = 0;
		parent::update($data, 'id = ' . (int)$id);
	}

	public function fetchAllByMenuId($menuId, array $options = null)
	{
		if(!is_numeric($menuId)) return false;

		//TODO : if is connected
		return $this->fetchAll(array('category_id = ?'=>$menuId,'isvisible'=>1))->toArray();


		//TODO else 'isvisible = 1'
		//return parent::fetchAll(array('isvisible = 1','category_id = ?'=>$categoryId))->toArray();
	}

	/**
	 * Retourne la liste des catégories d'un site.
	 * Si aucun site n'est donné (site=default), alors retourne la liste des catégories assigné à aucun site
	 * @return unknown_type
	 */
	public function fetchAllCategories($options = null)
	{
		$config = Zend_Registry::get('config');
		$sites = Zend_Registry::get('sites');
		$request = Zend_Controller_Front::getInstance()->getRequest();
		$site = $request->getParam('site');

		$where = " 1 ";
		if($options['isvisible'] == 1)
		$where .=" AND visible = 1 ";
		if($site == $config->site->default) {
			$sql = "	SELECT	*
						FROM	page_category WHERE site_id = 0";
			$categories = $this->_db->fetchAll($sql);
		}
		else if(isset($sites[$site]['id'])){
			$sql = "	SELECT	*
						FROM	page_category WHERE site_id = " . (int)$sites[$site]['id'];
			$categories = $this->_db->fetchAll($sql);
		}
	}

	public function fetchUncategorized($isVisible = 1)
	{
		$siteId = App_Functions::getSiteId();
		if($siteId){
		$sql = "	SELECT	*
					FROM	page 
					WHERE 	isvisible 		= $isVisible AND
							site_id 		= $siteId";
		
		//echo $sql;
		$pages = $this->_db->fetchAll($sql);
		//print_r($pages);
		return $pages;
		}
		return;
	}

	public function getVisibleCategories()
	{
		$options = array();
		$options['isvisible'] = 1;

		return $this->fetchAllCategories($options);
	}
}
